<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="800px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      label-position="right"
    >
      <el-tabs v-model="activeTab">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="数据源名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入数据源名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据源类型">
                <el-input :value="'WebSocket'" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入数据源描述"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-tab-pane>

        <!-- 连接配置 -->
        <el-tab-pane label="连接配置" name="connection">
          <el-form-item label="WebSocket地址" prop="connectionConfig.url">
            <el-input v-model="formData.connectionConfig.url" placeholder="请输入WebSocket地址">
              <template #prepend>ws://</template>
            </el-input>
          </el-form-item>

          <el-form-item label="协议类型" prop="connectionConfig.protocols">
            <el-select
              v-model="formData.connectionConfig.protocols"
              multiple
              placeholder="请选择子协议"
              style="width: 100%"
            >
              <el-option label="MQTT" value="mqtt" />
              <el-option label="STOMP" value="stomp" />
              <el-option label="自定义协议" value="custom" />
            </el-select>
          </el-form-item>

          <el-form-item label="请求头" prop="connectionConfig.headers">
            <el-button
              type="primary"
              size="small"
              @click="addHeader"
              style="margin-bottom: 10px"
            >
              添加请求头
            </el-button>
            <el-table
              :data="formData.connectionConfig.headers"
              border
              style="width: 100%"
              empty-text="暂无请求头配置"
            >
              <el-table-column prop="key" label="键名" width="200">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.key"
                    placeholder="请输入键名"
                    @change="validateHeaders"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="value" label="键值">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.value"
                    placeholder="请输入键值"
                    @change="validateHeaders"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ $index }">
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeHeader($index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-form-item label="心跳间隔(秒)" prop="connectionConfig.heartbeatInterval">
            <el-input-number
              v-model="formData.connectionConfig.heartbeatInterval"
              :min="0"
              :max="300"
              controls-position="right"
              style="width: 100%"
            />
            <span class="el-form-item__tip">0表示不发送心跳</span>
          </el-form-item>

          <el-form-item label="自动重连" prop="connectionConfig.reconnect">
            <el-switch v-model="formData.connectionConfig.reconnect" />
          </el-form-item>

          <el-form-item label="重连间隔(秒)" prop="connectionConfig.reconnectInterval" v-if="formData.connectionConfig.reconnect">
            <el-input-number
              v-model="formData.connectionConfig.reconnectInterval"
              :min="1"
              :max="60"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="最大重连次数" prop="connectionConfig.maxReconnectAttempts" v-if="formData.connectionConfig.reconnect">
            <el-input-number
              v-model="formData.connectionConfig.maxReconnectAttempts"
              :min="1"
              :max="100"
              controls-position="right"
              style="width: 100%"
            />
            <span class="el-form-item__tip">0表示无限重连</span>
          </el-form-item>
        </el-tab-pane>

        <!-- 消息配置 -->
        <el-tab-pane label="消息配置" name="message">
          <el-form-item label="初始消息" prop="messageConfig.initMessage">
            <el-input
              v-model="formData.messageConfig.initMessage"
              type="textarea"
              :rows="3"
              placeholder="连接建立后发送的初始消息(JSON格式)"
            />
          </el-form-item>

          <el-form-item label="消息格式" prop="messageConfig.format">
            <el-select
              v-model="formData.messageConfig.format"
              placeholder="请选择消息格式"
              style="width: 100%"
            >
              <el-option label="JSON" value="JSON" />
              <el-option label="Text" value="TEXT" />
              <el-option label="Binary" value="BINARY" />
            </el-select>
          </el-form-item>

          <el-form-item label="编码格式" prop="messageConfig.encoding">
            <el-select
              v-model="formData.messageConfig.encoding"
              placeholder="请选择编码格式"
              style="width: 100%"
            >
              <el-option label="UTF-8" value="UTF-8" />
              <el-option label="GBK" value="GBK" />
              <el-option label="ISO-8859-1" value="ISO-8859-1" />
            </el-select>
          </el-form-item>

          <el-form-item label="消息处理器" prop="messageConfig.handler">
            <el-input
              v-model="formData.messageConfig.handler"
              type="textarea"
              :rows="5"
              placeholder="输入JavaScript处理函数，处理接收到的消息"
            />
            <span class="el-form-item__tip">函数参数为(message)，需返回处理后的数据</span>
          </el-form-item>
        </el-tab-pane>

        <!-- 高级配置 -->
        <el-tab-pane label="高级配置" name="advanced">
          <el-form-item label="缓存配置" prop="cacheConfig.enabled">
            <el-switch
              v-model="formData.cacheConfig.enabled"
              active-text="启用缓存"
              inactive-text="禁用缓存"
            />
          </el-form-item>
          <el-form-item
            v-if="formData.cacheConfig.enabled"
            label="缓存时间(秒)"
            prop="cacheConfig.ttl"
          >
            <el-input-number
              v-model="formData.cacheConfig.ttl"
              :min="60"
              :max="86400"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="消息过滤" prop="filterConfig.enabled">
            <el-switch
              v-model="formData.filterConfig.enabled"
              active-text="启用过滤"
              inactive-text="禁用过滤"
            />
          </el-form-item>
          <template v-if="formData.filterConfig.enabled">
            <el-form-item label="过滤条件" prop="filterConfig.condition">
              <el-input
                v-model="formData.filterConfig.condition"
                type="textarea"
                :rows="3"
                placeholder="输入JavaScript条件表达式，例如: message.temperature > 30"
              />
            </el-form-item>
          </template>

          <el-form-item label="消息转换" prop="transformConfig.enabled">
            <el-switch
              v-model="formData.transformConfig.enabled"
              active-text="启用转换"
              inactive-text="禁用转换"
            />
          </el-form-item>
          <template v-if="formData.transformConfig.enabled">
            <el-form-item label="转换脚本" prop="transformConfig.script">
              <el-input
                v-model="formData.transformConfig.script"
                type="textarea"
                :rows="5"
                placeholder="输入JavaScript转换脚本，例如: return { ...message, processed: true }"
              />
            </el-form-item>
          </template>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'WebSocketSourceEditor',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      default: null
    }
  },
  emits: ['update:modelValue', 'submit'],
  setup(props, { emit }) {
    const visible = computed({
      get: () => props.modelValue,
      set: (val) => emit('update:modelValue', val)
    })

    const title = computed(() => 
      props.editData ? '编辑WebSocket数据源' : '新增WebSocket数据源'
    )

    const activeTab = ref('basic')
    const formRef = ref(null)

    // 默认表单数据
    const defaultFormData = {
      id: '',
      name: '',
      description: '',
      status: 1,
      connectionConfig: {
        url: '',
        protocols: [],
        headers: [],
        heartbeatInterval: 30,
        reconnect: true,
        reconnectInterval: 5,
        maxReconnectAttempts: 10
      },
      messageConfig: {
        initMessage: '',
        format: 'JSON',
        encoding: 'UTF-8',
        handler: 'function(message) {\n  // 处理消息逻辑\n  return message;\n}'
      },
      cacheConfig: {
        enabled: true,
        ttl: 3600
      },
      filterConfig: {
        enabled: false,
        condition: ''
      },
      transformConfig: {
        enabled: false,
        script: ''
      }
    }

    const formData = ref(JSON.parse(JSON.stringify(defaultFormData)))

    // 表单验证规则
    const formRules = {
      name: [
        { required: true, message: '请输入数据源名称', trigger: 'blur' },
        { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
      ],
      'connectionConfig.url': [
        { required: true, message: '请输入WebSocket地址', trigger: 'blur' },
        { 
          validator: (rule, value, callback) => {
            if (!value) return callback()
            try {
              new URL(value.startsWith('ws') ? value : `ws://${value}`)
              callback()
            } catch (e) {
              callback(new Error('请输入有效的WebSocket地址'))
            }
          },
          trigger: 'blur'
        }
      ],
      'connectionConfig.headers': [
        {
          validator: (rule, value, callback) => {
            if (!value || value.length === 0) return callback()
            const hasEmpty = value.some(item => !item.key || !item.value)
            if (hasEmpty) {
              callback(new Error('请求头键名和键值不能为空'))
            } else {
              callback()
            }
          },
          trigger: 'change'
        }
      ],
      'messageConfig.format': [
        { required: true, message: '请选择消息格式', trigger: 'change' }
      ],
      'cacheConfig.ttl': [
        { required: true, message: '请输入缓存时间', trigger: 'blur' }
      ]
    }

    // 添加请求头
    const addHeader = () => {
      formData.value.connectionConfig.headers.push({
        key: '',
        value: ''
      })
    }

    // 删除请求头
    const removeHeader = (index) => {
      formData.value.connectionConfig.headers.splice(index, 1)
      validateHeaders()
    }

    // 验证请求头
    const validateHeaders = () => {
      formRef.value.validateField('connectionConfig.headers')
    }

    // 对话框关闭
    const handleClosed = () => {
      formRef.value?.resetFields()
      formData.value = JSON.parse(JSON.stringify(defaultFormData))
    }

    // 提交表单
    const submitForm = async () => {
      try {
        await formRef.value.validate()
        
        // 处理请求头，过滤空值
        const finalData = JSON.parse(JSON.stringify(formData.value))
        finalData.connectionConfig.headers = finalData.connectionConfig.headers
          .filter(item => item.key && item.value)
        
        // 验证初始消息是否为有效JSON
        if (finalData.messageConfig.initMessage && finalData.messageConfig.format === 'JSON') {
          try {
            JSON.parse(finalData.messageConfig.initMessage)
          } catch (e) {
            throw new Error('初始消息必须是有效的JSON格式')
          }
        }
        
        emit('submit', finalData)
        visible.value = false
      } catch (error) {
        console.error('表单验证失败:', error)
        ElMessage.error(error.message || '请检查表单填写是否正确')
      }
    }

    // 监听编辑数据变化
    watch(() => props.editData, (newVal) => {
      if (newVal) {
        formData.value = JSON.parse(JSON.stringify({
          ...defaultFormData,
          ...newVal,
          connectionConfig: {
            ...defaultFormData.connectionConfig,
            ...(newVal.connectionConfig || {})
          },
          messageConfig: {
            ...defaultFormData.messageConfig,
            ...(newVal.messageConfig || {})
          },
          cacheConfig: {
            ...defaultFormData.cacheConfig,
            ...(newVal.cacheConfig || {})
          },
          filterConfig: {
            ...defaultFormData.filterConfig,
            ...(newVal.filterConfig || {})
          },
          transformConfig: {
            ...defaultFormData.transformConfig,
            ...(newVal.transformConfig || {})
          }
        }))
        
        // 确保headers是数组
        if (!Array.isArray(formData.value.connectionConfig.headers)) {
          formData.value.connectionConfig.headers = []
        }
      }
    }, { immediate: true })

    return {
      visible,
      title,
      activeTab,
      formRef,
      formData,
      formRules,
      addHeader,
      removeHeader,
      validateHeaders,
      handleClosed,
      submitForm
    }
  }
}
</script>

<style scoped>
.el-input-with-prepend :deep(.el-input-group__prepend) {
  width: 80px;
}

.el-form-item__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  display: inline-block;
}
</style>